package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin()// 自定义自己编写的登录页面
//            .loginPage("/login.html")// 登录页面设置
//            .loginProcessingUrl("/user/login")// 登录访问路径
//            .defaultSuccessUrl("/test/index").permitAll()// 登录成功后跳转的路径
            .and().authorizeRequests()
                .antMatchers("/","/test/hello","/user/login").permitAll()
                .antMatchers("/test/index")
//                .hasAuthority("admins")// 表示当前的用户具有admins这个权限才能访问 但只能是单个权限
//                .hasAnyAuthority("admins,manager")// 可以多个权限
//                .hasRole("role")// 需要手动加一个ROLE_前缀
                .hasAnyRole("role")
//                .anyRequest().authenticated()
            .and().csrf().disable();// 关闭csrf防护
    }
}
